const MiddlewareEventEmitter = require('../utils/MiddlewareEventEmitter');
global.utils = require('../utils/util.js'); // 不依赖项目模块的工具函数
require('./config.js');
global.CONSTANTS = require('./constants.js'); // 依赖配置项 设定运行时常量

const WebsocketServer = require("../ws_frame/server/server.js");
const { ClientsManager, ClientManager } = require('./class/ClientsManager.js');
global.WSS = new WebsocketServer(
    {   
        name: CONF.CONFIG.get('Websocket')['ServerName'],
        port: CONF.CONFIG.get('Websocket')['Port'],
        connectKey: CONF.CONFIG.get('Websocket')['ConnectKey'],
        // 自定义客户端管理器, 为空则采用默认管理器
        ClientsManager: ClientsManager,
        ClientManager: ClientManager,
        enableConsoleCmd: CONSTANTS.RUNMODE == 'NODEJS',
        heartBeatInterval: CONF.CONFIG.get('Websocket')?.['HeartBeatInterval'] ?? 10000,
        heartBeatTimeoutCount: CONF.CONFIG.get('Websocket')?.['HeartBeatTimeoutCount'] ?? 2,
    }
);

// 设置日志
if (CONF.CONFIG.get('Websocket')['Debug'] == true){
    WSS.logger.setConsole(true, 5);
    WSS.logger.debug(`### WS协调服务端Debug模式开启 ###`);
}

WSS.on('serverstart', ()=>{
    WSS.logger.info('WS协调服务端版本: ' + VERSION.join('.'));
});

// 初始化回环监听器
WSS.api = {
    listener: new MiddlewareEventEmitter(),
    remoteCallFunctions: {} // 导入的其他插件的监听函数
};
WSS.addApiEventName = function addApiEventName(eventName){
    this.api.remoteCallFunctions[eventName] = {};
    return true;
};

// 加载路由
require('./router/router.js');

// llapi模块
require('./llapi.js');

// 加载控制台命令
if (WSS.enableConsoleCmd){
    require('./consoleCmd.js');
}
if (typeof ll !== 'undefined'){
    ll.onUnload(()=>{
        WSS.close();
    });
}

WSS.start();
